using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;

namespace PokerStar.Core
{
    public static class MathHelper
    {
        /// <summary>
        /// refer http://en.wikipedia.org/wiki/Combination
        /// </summary>
        public static void GenerateCombinations<T>(IList<T> list, int n, int k, [Out]IList<IList<T>> combination)
        {
            if (list == null)
                throw new ArgumentNullException("list");
            if (combination == null)
                throw new ArgumentNullException("combination");
            if (n == 0)
                throw new ArgumentOutOfRangeException("n");
            if (k == 0)
                throw new ArgumentOutOfRangeException("k");
            if (n <= k)
                throw new ArgumentException("n should be larger than k");
            if (n != list.Count)
                throw new ArgumentException("n should be equal to list.Count");

            CalcCombination(list, null, 0, k, combination);
        }

        private static void CalcCombination<T>(IList<T> list, IList<T> precomb, int c, int k, IList<IList<T>> combination)
        {
            if (precomb == null)
                precomb = new List<T>(k);

            if (precomb.Count == k)
            {
                combination.Add(precomb);
                return;
            }

            int max = list.Count - k + precomb.Count;
            for (int i = c; i <= max; i++)
            {
                var copy = precomb.ToList();
                copy.Add(list[i]);
                CalcCombination(list, copy, i + 1, k, combination);
            }
        }
    }
}